package com.xiaoye.qbproject.controller.qbzyk;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoye.qbproject.config.XiaoYeConfig;
import com.xiaoye.qbproject.controller.base.BaseController;
import com.xiaoye.qbproject.domain.AjaxResult;
import com.xiaoye.qbproject.domain.BlbcTroops;
import com.xiaoye.qbproject.page.TableDataInfo;
import com.xiaoye.qbproject.redis.RedisCache;
import com.xiaoye.qbproject.service.BlbcTroopsService;
import com.xiaoye.qbproject.util.StringUtils;
import com.xiaoye.qbproject.util.poi.ExcelUtil;
import com.xiaoye.qbproject.util.poi.TroopsV2ExcelUtil;
import com.xiaoye.qbproject.util.uuid.UUID;
import com.xiaoye.qbproject.vo.TroopsImportVo;
import com.xiaoye.qbproject.vo.TroopsV2ImportVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author : ChenYao
 * @version : 1.0
 * @description : 兵力编程编组
 * @create : 2024-12-30 11:40
 */
@Slf4j
@RestController
@RequestMapping("/blbc")
public class BlbcTroopsController extends BaseController {

    @Autowired
    private BlbcTroopsService blbcTroopsService;
    @Autowired
    private RedisCache redisCache;

    /***
     * @description: 列表查询
     * @author: ChenYao
     * @param blbcTroops
     * @return: com.xiaoye.qbproject.page.TableDataInfo
     * @ceateDate: 2024-12-30 11:43
     */

    @GetMapping("/list")
    public TableDataInfo list(BlbcTroops blbcTroops) {
        startPage();
        String troopsName = blbcTroops.getTroopsName();
        String countryId = blbcTroops.getCountryId();
        LambdaQueryWrapper<BlbcTroops> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(troopsName)) {
            queryWrapper.like(BlbcTroops::getTroopsName, troopsName);
        }
        if (StringUtils.isNotBlank(countryId)) {
            queryWrapper.eq(BlbcTroops::getCountryId, countryId);
        }
        List<BlbcTroops> list = blbcTroopsService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * @description: 编成编组, 树形结构
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2024-12-30 12:35
     */

    @GetMapping("/tree")
    public AjaxResult tree() {
        List<BlbcTroops> tree = blbcTroopsService.tree();
        return AjaxResult.success(tree);
    }

    @GetMapping("/{id}")
    public AjaxResult getBlbc(@PathVariable("id") String id) {
        return success(blbcTroopsService.getById(id));
    }

    @PostMapping
    public AjaxResult saveBlbc(@RequestBody @Validated BlbcTroops blbcTroops) {
        blbcTroopsService.saveOrUpdate(blbcTroops);
        blbcTroopsService.delCache();
        return success();
    }

    @PutMapping
    public AjaxResult updateBlbc(@RequestBody @Validated BlbcTroops blbcTroops) {
        blbcTroopsService.updateById(blbcTroops);
        blbcTroopsService.delCache();
        return success();
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteBlbc(@PathVariable("id") String id) {
        blbcTroopsService.removeById(id);
        blbcTroopsService.delCache();
        return success();
    }

    @PostMapping("importInfo")
    public AjaxResult importInfo(@RequestParam("file") MultipartFile file) throws IOException {
        ExcelUtil<TroopsImportVo> util = new ExcelUtil<TroopsImportVo>(TroopsImportVo.class);
        List<TroopsImportVo> blbcTroops = util.importExcel(file.getInputStream());
        blbcTroopsService.importTroops(blbcTroops);
        blbcTroopsService.delCache();
        return success();
    }

    @PostMapping(value = "/exportOwl/{countryId}", produces = MediaType.TEXT_XML_VALUE)
    public void exportOwl(@PathVariable String countryId, HttpServletResponse response) {
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachment; filename=\"BLBC_TROOPS_" + UUID.fastUUID() + ".owl\"");
        response.setHeader("Content-Type", "application/xml;charset=UTF-8");
        log.info("开始导出兵力编程编组数据...countryId:{}", countryId);
        // 调用服务方法导出数据
        blbcTroopsService.exportOwl(countryId, response);
    }

    @PostMapping(value = "importInfoV2", consumes = "multipart/form-data")
    public AjaxResult importInfoV2(MultipartFile file) {
        // 获取文件名
        String filename = file.getOriginalFilename();
        File file1 = new File(XiaoYeConfig.getImportPath() + File.separator + filename);
        file1.getParentFile().mkdirs();
        try {
            file.transferTo(file1);
            // 请求中获取上传的文件
            TroopsV2ExcelUtil excelUtil = new TroopsV2ExcelUtil();
            Map<String, Object> sheetZbImportVoMap = excelUtil.readExcelMuchSheetToObj(file1.getPath());
            sheetZbImportVoMap.forEach((key, value) -> {
                List<TroopsV2ImportVo> troopsV2ImportVos = (List<TroopsV2ImportVo>) value;
                blbcTroopsService.saveTroopsV2(troopsV2ImportVos, key);
            });
            blbcTroopsService.delCache();
            return success("导入成功");
        } catch (IOException e) {
            e.getLocalizedMessage();
            log.error("导入失败", e.getLocalizedMessage());
            return AjaxResult.error("上传失败");
        }
    }
}
